package com.seal.yoyoshop.filter;

import com.seal.yoyoshop.bin.Admin;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/admin/*")
public class AdminLoginFilter extends HttpFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest req = (HttpServletRequest) request;
        String path = req.getServletPath();
        if (path.contains("/css/") || path.contains("/js/") || path.contains("/layui/") || path.contains("/img/")) {
            chain.doFilter(request, response);
        } else {
            if (path.equals("/admin/login") || path.equals("/admin/login.jsp")) {
                chain.doFilter(request, response);
            }else {
                HttpSession session = req.getSession();
                Admin admin = (Admin) session.getAttribute("admin");
                if (admin != null) chain.doFilter(request, response);
                else {
                    HttpServletResponse resp = (HttpServletResponse) response;
                    resp.sendRedirect("/admin/login.jsp");
                }
            }

        }
    }
}
